package com.example.yyy

import android.Manifest
import android.app.DownloadManager
import android.content.Context
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.location.Criteria
import android.location.Location
import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_download_manager.*
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.json.JSONObject
import java.io.File
import java.net.URL
import java.text.MessageFormat


class DownloadManagerActivity : AppCompatActivity() {
    private val mapsUrl = "http://maps.google.cn/maps/api/geocode/json?latlng={0},{1}&sensor=true&language=zh-CN"
    private val imgUrl = "http://pic30.nipic.com/20130618/13036121_090222314159_2.jpg"
    private lateinit  var mLocation:Location
    private lateinit var  c:Cursor
    private var downSize:Long =0
    private val handler = Handler()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_download_manager)
//        mLocation=getLocation()
//        setLocationText(mLocation)
        getImage()
        downLoad()
    }

     //获取网络图片
    private fun getImage(){
         doAsync {
             val url = "$imgUrl"
             //获取指定url返回的字节数据
             val bytes = URL(url).readBytes()
             //解析
             val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
             //或者生成图片文件
             val path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString()+"/"
             val file_path ="$path${DateUtil.nowDate}.jpg"
             File(file_path).writeBytes(bytes)
             //回主线程不图片
             uiThread {
                 img_dla_httpImg.setImageBitmap(bitmap)
             }
         }
     }

    //下载管理器DownLoadManager

    private fun downLoad(){
        val downLoadMan = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        //声明下载任务的请求对象
        val down = DownloadManager.Request(Uri.parse("$imgUrl"))
        //指定通知栏的标题文本
        down.setTitle("下载信息")
        //指定通知栏的描述文本
        down.setDescription("图片下载中")
        //移动网络 or wifi可进行下载
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE or DownloadManager.Request.NETWORK_WIFI)
        //指定下载中和完成后都可见
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        //指定下载文件保存路径
        down.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,"图片.apk")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            down.setRequiresCharging(true)
        }
        //下载请求添加到下载队列
        val enqueueId = downLoadMan.enqueue(down)
        val query = DownloadManager.Query().setFilterById(enqueueId)
        c = downLoadMan.query(query)
        c.moveToFirst()
        handler.post(progressCircleUp)

    }

    private val progressCircleUp = object: Runnable {
        override fun run() {
            if(c!=null && c.moveToFirst()){
                downSize = c.getLong(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                val downingSize = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))

            runOnUiThread{
                tvpg_dla.setProgress((downingSize.toInt()/downSize.toInt())*100)
            }
            if (downingSize<=downingSize){
                handler.postDelayed(this,200)
            }
            }
        }

    }
    //通过GPS或WIFI获取位置
    private fun getLocation():Location{
        val loMan = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        var location:Location?= null
        val criteria = Criteria()
        criteria.accuracy = Criteria.ACCURACY_FINE //高精度
        criteria.isAltitudeRequired = false;
        criteria.isBearingRequired = false;
        criteria.isCostAllowed = true;
        criteria.powerRequirement = Criteria.POWER_LOW; // 低功耗
        val provider = loMan.getBestProvider(criteria, true)// 获取GPS信息
        val ok: Boolean = loMan.isProviderEnabled(LocationManager.GPS_PROVIDER)
        if (ok) { //开启了定位服务
            if (Build.VERSION.SDK_INT >= 23) {
                if (ContextCompat.checkSelfPermission(
                        this,
                        Manifest.permission.ACCESS_FINE_LOCATION
                    ) != PackageManager.PERMISSION_GRANTED
                ) {
                    //没有权限，现在申请权限
                } else {
                    location = loMan.getLastKnownLocation(LocationManager.GPS_PROVIDER)?:loMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)?:loMan.getLastKnownLocation(criteria.toString())?:throw IllegalStateException("获取失败")
                }
            } else {
                location = loMan.getLastKnownLocation(LocationManager.GPS_PROVIDER)?:loMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)?:throw IllegalStateException("获取失败1")
            }
        } else { //未开启定位服务
            location = loMan.getLastKnownLocation(LocationManager.GPS_PROVIDER)?:loMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)?:throw IllegalStateException("获取失败2")
        }
        return location!!
    }

    //位置监听器侦听到定位变化事件，就调用该函数请求详细地址
    private fun setLocationText(location: Location?) {
        if (location != null) {
            doAsync {
                //根据经纬度数据从谷歌地图获取详细地址信息
                val url = MessageFormat.format(mapsUrl, location.latitude, location.longitude)
                val text = URL(url).readText()
                Log.e("TAG", "getLocation1: $text" )
                val obj = JSONObject(text)
                val resultArray = obj.getJSONArray("results")
                var address = ""
                //解析json字符串，其中formatted_address字段为具体地址名称
                if (resultArray.length() > 0) {
                    val resultObj = resultArray.getJSONObject(0)
                    address = resultObj.getString("formatted_address")
                    Log.e("TAG", "getLocation: $location" )
                }
                //获得该地点的详细地址之后，回到主线程把地址显示在界面上
                uiThread { findAddress(location, address) }
            }
        } else {
            tv_dla_location.text = "$mLocation\n暂未获取到定位对象"
        }
    }

    //在主线程中把定位信息连同地址信息都打印到界面上
    private fun findAddress(location: Location, address: String) {
        tv_dla_location.text = "$mLocation\n定位对象信息如下： " +
                "\n\t时间：${DateUtil.nowDate}" +
                "\n\t经度：${location.longitude}，纬度：${location.latitude}" +
                "\n\t高度：${location.altitude}米，精度：${location.accuracy}米" +
                "\n\t地址：$address"
    }
}